import { defineEventHandler, H3Event } from 'h3'
import { recordLog } from '../util/log'

// 服务器中间件：在每个页面路由的请求（GET, Accept: text/html）时记录一条访问日志
export default defineEventHandler(async (event: H3Event) => {
  try {
    const nodeReq: any = (event as any).node && (event as any).node.req
    if (!nodeReq) return

    const method = (nodeReq.method || '').toUpperCase()
    const headers = nodeReq.headers || {}
    const accept = (headers['accept'] || headers['Accept'] || '') as string

    // 只记录页面导航（浏览器请求 HTML 的 GET 请求）
    if (method !== 'GET') return
    if (!accept.includes('text/html')) return

    // 路径过滤：忽略常见静态资源或内部接口
    const path = nodeReq.url || (event as any).path || ''
    const skipPrefixes = ['/api', '/_nuxt', '/_ipx', '/favicon', '/assets', '/images', '/sw.js']
    for (const p of skipPrefixes) {
      if (path.startsWith(p)) return
    }
    // 忽略带有文件扩展名的请求（静态资源）
    if (/\.[a-zA-Z0-9]{1,6}$/.test(path)) return

    // 获取客户端 IP（优先 X-Forwarded-For）
    const xff = headers['x-forwarded-for'] || headers['X-Forwarded-For']
    let ip = ''
    if (xff) {
      ip = String(xff).split(',')[0].trim()
    } else if (nodeReq.socket && nodeReq.socket.remoteAddress) {
      ip = nodeReq.socket.remoteAddress
    } else if (nodeReq.connection && nodeReq.connection.remoteAddress) {
      ip = nodeReq.connection.remoteAddress
    }

    const ua = headers['user-agent'] || headers['User-Agent'] || ''

    // 调用记录函数：把 IP 当作 username 存储
    await recordLog(event, {
      authority: 'access',
      message: `UA:${String(ua).slice(0, 500)}`,
      username: ip || undefined,
    })
  } catch (e) {
    // 不要抛出错误以免影响正常请求
    try { console.warn && console.warn('[access-log] error', e) } catch (ee) { /* ignore */ }
  }
})
